package com.detrum.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.detrum.adapter.ShareGridAdapter;
import com.detrum.base.R;
import com.detrum.bean.ShareBean;
import com.detrum.service.DownloadDeviceService;
import com.detrum.service.DownloadService;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created by abc on 2017/7/24.
 */

public class MyMethod {

    public interface MyMethodCall {
        void Confirm();

        void Cancel();
    }

    public interface MyMethodCall2 {
        void UpData();
    }

    //直接跳转新的Activity
    public static void toActivity(Context context, Class mClass) {
        Intent intent = new Intent(context, mClass);
        context.startActivity(intent);
    }

    //带参数跳转新的Activity
    public static void toActivity(Context context, Class mClass, String[] keys, String[] values) {
        Intent intent = new Intent(context, mClass);
        if (keys != null && values != null && keys.length == values.length) {
            for (int i = 0; i < keys.length; i++) {
                intent.putExtra(keys[i], values[i]);
            }
        }
        context.startActivity(intent);
    }

    //带参数跳转新的Activity
    public static void toActivity(Context context, Class mClass, String[] keys, int[] values) {
        Intent intent = new Intent(context, mClass);
        if (keys != null && values != null && keys.length == values.length) {
            for (int i = 0; i < keys.length; i++) {
                intent.putExtra(keys[i], values[i]);
            }
        }
        context.startActivity(intent);
    }

    public static String[] getDateArray(int timeStamp) {
        LogUtils.i("MyMethod " + "timeStamp===" + timeStamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒", Locale.CHINA);
        String datetimes = dateFormat.format(new Date(timeStamp * 1000L));
        String[] fenge = datetimes.split("[年月日时分秒]");
        return fenge;
    }

    /**
     * 根据传递的类型格式化时间
     *
     * @param timestamp 时间戳
     * @param type      例如：yy-MM-dd
     * @return
     */
    public static String getDateTimeByMillisecond(long timestamp, String type) {

        Date date = new Date(timestamp);

        SimpleDateFormat format = new SimpleDateFormat(type);

        String time = format.format(date);

        return time;
    }

    /**
     * 将格式化数字字符串转换为时间戳
     */
    public static long getTimeStamp(String time, String type) {
        long timestamp = -1;
        TimeZone tz = TimeZone.getDefault();
        int offset = tz.getRawOffset();
        SimpleDateFormat format = new SimpleDateFormat(type);
        try {
            Date date = format.parse(time);
            timestamp = date.getTime();
        } catch (ParseException e) {
            LogUtils.i("e = " + e.getMessage());
            e.printStackTrace();
        }
        return timestamp+offset;
    }

    /**
     * 判断网络是否连接.
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return mNetworkInfo != null && mNetworkInfo.isAvailable();
    }

    /**
     * 判断设备网络是否连接.
     */
    public static boolean isDevcieConnected(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return mNetworkInfo != null && mNetworkInfo.getExtraInfo().contains("DCAM");
    }

    /**
     * 判断是否存在某个包.
     */
    public static boolean isPkgInstalled(Context context, String pkgName) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 批量获得view内的value
     * 主要用于批量TextView获取数据
     *
     * @param tvs view数组
     * @return 得到的值的数组
     * @throws NoSuchMethodException     找不到该方法的异常
     * @throws InvocationTargetException 调用目标异常
     * @throws IllegalAccessException    类型转换异常
     */

    public static String[] getTextS(View... tvs) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String[] strs = new String[tvs.length];
        Method method = tvs[0].getClass().getDeclaredMethod("getText", new Class[]{});
        LogUtils.i("MyMethod" + " method==" + method);
        for (int i = 0; i < tvs.length; i++) {
            /**
             * 利用反射循环加载数据
             */

            strs[i] = (String) method.invoke(tvs[i], new Object[]{});
        }
        return strs;
    }

    public static Dialog GetDialog(Context context, int msg) {
        Dialog dialog = new AlertDialog.Builder(context, R.style.loading_dialog)
                .setMessage(msg)
                .create();
        dialog.show();
        return dialog;
    }

    public static void ShowDialog(Context context, int msg) {
        new AlertDialog.Builder(context, R.style.loading_dialog)
                .setMessage(msg)
                .setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create()
                .show();
    }

    public static void ShowDialogDelete(Context context, String msg, final MyMethodCall myMethodCall) {
        new AlertDialog.Builder(context).setMessage(msg).setNegativeButton(R.string.delete, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                myMethodCall.Confirm();
            }
        }).setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                myMethodCall.Cancel();
            }
        }).show();
    }

    public static void ShowDialogLogin(final Context context, final Class mClass) {
        new AlertDialog.Builder(context).setMessage("账号在其他地方登录，请重新登录修改密码").setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                toActivity(context, mClass);
                dialogInterface.dismiss();
                ((Activity) context).finish();
            }
        }).show();
    }

    public static void ShowDialogNet(final Context context) {
        new AlertDialog.Builder(context).setMessage("网络连接故障").setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).show();
    }

    public static void ShowDiaLogFinish(final Activity context, int msg) {
        new AlertDialog.Builder(context,R.style.loading_dialog)
                .setMessage(msg)
                .setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        context.finish();
                    }
                })
                .create()
                .show();
    }

    public static void ShowDialog(final Activity context, String msg) {
        new AlertDialog.Builder(context).setMessage(msg).setNegativeButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).show();
    }

    public static void ShowMsgDialog(final Context context, int msg, final MyMethodCall2 myMethodCall2) {
        new AlertDialog.Builder(context,R.style.loading_dialog)
                .setMessage(msg)
                .setNegativeButton(R.string.updata, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        myMethodCall2.UpData();
                        dialogInterface.dismiss();
                    }
                })
                .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    public static void ShowShareDialog(final Context context, final List<ShareBean> beanList, final Uri fileUri) {
        View view = LayoutInflater.from(context).inflate(R.layout.share_gridview, null, false);
        GridView gridView = view.findViewById(R.id.gridView);
        ShareGridAdapter shareGridAdapter = new ShareGridAdapter(context, beanList);
        gridView.setAdapter(shareGridAdapter);
        new AlertDialog.Builder(context,R.style.loading_dialog)
                .setView(view)
                .create()
                .show();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ComponentName componentName = new ComponentName(beanList.get(position).getPackageName(), beanList.get(position).getActivityName());
                Intent i = new Intent(Intent.ACTION_SEND);
                i.putExtra(Intent.EXTRA_STREAM, fileUri);
                i.setType("image/jpeg");
                i.setComponent(componentName);
                context.startActivity(i);
                LogUtils.i("fileUri == " + fileUri);
                LogUtils.i("点击了" + beanList.get(position).getName());
            }
        });
    }

    public static void ShowShareDialog2(final Context context, final List<ShareBean> beanList, final ArrayList<Uri> uris) {
        View view = LayoutInflater.from(context).inflate(R.layout.share_gridview, null, false);
        GridView gridView = view.findViewById(R.id.gridView);
        ShareGridAdapter shareGridAdapter = new ShareGridAdapter(context, beanList);
        gridView.setAdapter(shareGridAdapter);
        new AlertDialog.Builder(context,R.style.loading_dialog)
                .setView(view)
                .create()
                .show();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ComponentName componentName = new ComponentName(beanList.get(position).getPackageName(), beanList.get(position).getActivityName());
                Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
                i.putExtra(Intent.EXTRA_STREAM, uris);
                i.setType("image/*");
                i.setComponent(componentName);
                context.startActivity(i);
                LogUtils.i("uris.size == " + uris.size());
                LogUtils.i("点击了" + beanList.get(position).getName());
            }
        });
    }

    public static void ShowDiaLogDownload(final Context context, String str) {
        new AlertDialog.Builder(context,R.style.loading_dialog)
                //.setTitle(R.string.new_version)
                .setMessage(str)
                .setNegativeButton(R.string.download, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        context.startService(new Intent(context, DownloadService.class));
                        dialogInterface.dismiss();

                    }
                })
                .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    public static void ShowDialogDownloadDevice(final Context context, String str) {
        new AlertDialog.Builder(context,R.style.loading_dialog)
                //.setTitle(R.string.new_device_version)
                .setMessage(str)
                .setNegativeButton(R.string.download, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        context.startService(new Intent(context, DownloadDeviceService.class));
                        dialogInterface.dismiss();

                    }
                })
                .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    public static void saveSharedPreferences(final Context context, String[] key, boolean[] isLaunch) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("state", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (key.length == isLaunch.length) {
            for (int i = 0; i < key.length; i++) {
                editor.putBoolean(key[i], isLaunch[i]);
            }
            editor.commit();
        } else {
            LogUtils.i("键值对不匹配");
        }
    }

    public static boolean[] getisLaunch(final Context context, String[] key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("state", Context.MODE_PRIVATE);
        boolean[] values = new boolean[key.length];
        for (int i = 0; i < values.length; i++) {
            values[i] = sharedPreferences.getBoolean(key[i], false);
        }
        return values;
    }

    public static void saveVersion(final Context context, String[] keys, String[] values) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("version", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (keys.length == values.length) {
            for (int i = 0; i < keys.length; i++) {
                editor.putString(keys[i], values[i]);
            }
            editor.commit();
        } else {
            LogUtils.i("键值对不匹配");
        }
    }

    public static String[] getVersion(final Context context, String[] keys) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("version", Context.MODE_PRIVATE);
        String[] values = new String[keys.length];
        for (int i = 0; i < values.length; i++) {
            values[i] = sharedPreferences.getString(keys[i], "");
        }
        return values;
    }

    public static void saveSelectItem(final Context context, String[] keys, boolean[] values) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("select", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (keys.length == values.length) {
            for (int i = 0; i < keys.length; i++) {
                editor.putBoolean(keys[i], values[i]);
            }
            editor.commit();
        } else {
            LogUtils.i("键值对不匹配");
        }
    }

    public static boolean[] getSelectItem(final Context context, String[] keys) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("select", Context.MODE_PRIVATE);
        boolean[] values = new boolean[keys.length];
        for (int i = 0; i < values.length; i++) {
            values[i] = sharedPreferences.getBoolean(keys[i], false);
        }
        return values;
    }

    public static String getValue(Context context, String name, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        String value = sharedPreferences.getString(key, "");
        return value;
    }

    public static void saveSingleValue(Context context, String name, String key, String value) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static int getNum(Context context, String name, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        int value = sharedPreferences.getInt(key, 0);
        return value;
    }

    public static void saveSingleValue(Context context, String name, String key, int value) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, value);
        editor.commit();
    }

    /**
     * 得到自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     */
    public static Dialog createLoadingDialog(Context context, int msg) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog, null, false);// 得到加载view
        FrameLayout layout = v.findViewById(R.id.dialog_view);// 加载布局

        TextView tipTextView = v.findViewById(R.id.tipTextView);// 提示文字

        // 使用ImageView显示动画
        tipTextView.setText(msg);// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog

        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        return loadingDialog;

    }
}
